import { utils } from "./Utils";
import PlatUtils from "./PlatUtils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameItem extends cc.Component {

    /*
    {
		"icon": "http://ff.td68x.com/xcx/ylyxhz/451m.png",
		"name": "点亮它的色彩",
		"path": "",
		"qr_code": "",
		"app_id": "wx35562d816d9ed9fb"
    }
    */
    data: any = null;

    icon: cc.Sprite = null;
    labelName: cc.Label = null;
    labelShadow: cc.Label = null;

    _isContentFilled:boolean = false;

    onLoad() {
        let mask = this.node.getChildByName("Mask");
        this.icon = mask.getChildByName("Icon").getComponent(cc.Sprite);
        this.labelName = this.node.getChildByName("Label").getComponent(cc.Label);
        this.labelShadow = this.node.getChildByName("LabelShadow").getComponent(cc.Label);
    }

    public init(data: any) {
        this.data = data;
    }

    update(dt: number){
        if(!this._isContentFilled){
            this.updateItem();
        }
    }

    onEnable() {
        this.node.on(cc.Node.EventType.TOUCH_END, (event: cc.Event) => {
            if(this.data.app_id){
                utils.wechatTool.navigateToMiniProgram(this.data.app_id);
            }else{
                if(this.data.qr_code){
                    utils.wechatTool.previewImage(this.data.qr_code);
                }
            }
        }, this);
    }

    onDisable() {
        this.node.targetOff(this);
    }

    updateItem() {
        if(PlatUtils.IsWechat){
            if (this.data) {
                this._isContentFilled = true;
                
                if (this.data.name) {
                    let gameName: string = this.data.name;
                    if (this.data.name.length > 4) {
                        gameName = gameName.slice(0, 4);
                        gameName += "...";
                    }
                    this.labelName.string = gameName;
                    this.labelShadow.string = gameName;
                }
    
                if (this.data.icon) {
                    if (PlatUtils.IsWechat) {
                        let self = this;
                        cc.loader.load(this.data.icon, function (err, texture) {
                            if(!err){
                                self.icon.spriteFrame = new cc.SpriteFrame(texture);
                            }
                        });
    
                    }
                }
            }
        }
        
    }
}
